const initAcceptAnswerMod = ({ oldVal, newVal }) => ({
  oldVal: oldVal.id
    ? { commentId: oldVal.id, author: oldVal.user }
    : undefined,
  newVal: {
    commentId: newVal.id,
    author: newVal.user, // id nickname avatar
  },
});

const initMod = (log) => {
  const hash = log.modify_hash;
  if (!hash) return {};
  if (['change_title', 'change_content'].includes(log.action)) {
    return {
      oldVal: hash.old_val,
      newVal: hash.new_val,
    };
  }
  let [oldVal, newVal, errMsg] = [hash.old_val, hash.new_val, ''];
  try { oldVal = JSON.parse(oldVal); } catch (err) { console.warn(errMsg = err); }
  try { newVal = JSON.parse(newVal); } catch (err) { console.warn(errMsg = err); }

  if (errMsg) return { oldVal, newVal, errMsg };
  if (log.action === 'accept_answer') return initAcceptAnswerMod({ oldVal, newVal });

  return { oldVal, newVal, errMsg };
};

export const formatIssueLogItem = log => ({
  id: log.id,
  type: log.type,
  modifier: log.user || {}, // id nickname avatar
  action: log.action,
  mod: initMod(log), // old_val new_val

  created_at: log.created_at,
  updated_at: log.updated_at,
});

export default formatIssueLogItem;
